import axios from 'axios'
import router from '@/router'
import tipMessage from '@/utils/tipMessage'
import store from '../store/index.js'
import { solarPowerSystem } from '@/common/projectAlias'
/**
 * 提示函数
 */
const tip = msg => {
  tipMessage(msg, 'error')
}

/**
 * 请求失败后的错误统一处理
 * @param status 请求失败的状态码,这块还没设置
 * @param msg 接口失败返回的说明
 */
 const errorHandle = (status, msg) => {
  switch (status) {
      case 500:
          tip(msg || '服务错误');
          break;
      case 502:
          tip(msg || '接口缺失，请联系管理员');
          break;
      case 401:
          tip('登录超时，请重新登录！');
          sessionStorage.removeItem('aiUserMessage');
          router.push('/login');
          break;
      case 404:
          tip(msg || '找不到接口，请联系管理员！');
          break;
      case 421:
          tip('登录超时，请重新登录！');
          sessionStorage.removeItem('aiUserMessage');
          router.push('/login');
          break;
      case "421":
          tip('登录超时，请重新登录！');
          sessionStorage.removeItem('aiUserMessage');
          router.push('/login');
          break;
      default:
          tip(msg || '未知错误');
          break;
  }
};
/**
 * 将外部的状态码进行一个处理
 * @param msg   外部服务器错误的一个信息
 */
const dealCode = msg => {
  let code = null
  if (msg.indexOf('404') > -1) code = 404
  if (msg.indexOf('500') > -1) code = 500
  if (msg.indexOf('502') > -1) code = 502
  return code
}

/**
 * axios基础设置
 * @type {number}
 */
axios.defaults.timeout = 30000

//创建axios实例
const instance = axios.create({})

/**
 * 请求拦截
 */
instance.interceptors.request.use(
  config => {
    config.headers["X-Tbd-Token"] = sessionStorage.aiUserMessage ? JSON.parse(sessionStorage.aiUserMessage).aiSessionId : '';
    //菜单code
    config.headers['menuCode'] = router.currentRoute.value?.meta?.menuCode ?? ''
    //应用别名
    config.headers['projectAlias'] = solarPowerSystem
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截
 */
instance.interceptors.response.use(
  response => {
    //内部  请求 || 导出
    // console.log('response',response);
    if ((response.status === 200 && response.data.success) || (response.status === 200 && response.data.type) || (response.status === 200 && response.data.status === 'success')) {
      let result = response.data //本地文件的请求
      if (response.data.success) result = response.data.data
      return Promise.resolve(result)
    } else {
      errorHandle(response.data.error_code, response.data.error_msg)
      return Promise.reject(response)
    }
  },
  error => {
    //外部
    let code = dealCode(error.message)
    errorHandle(code)
    return Promise.reject(error)
  }
)

export default instance
